<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/4/5
 * Time: 9:05
 */

namespace app\api\service;


use app\api\model\User;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

class DeliveryMessage extends WxMessage
{
    // 处理模板消息的相关业务逻辑

    // 微信模板消息id-订单发货提醒
    const DELIIVERY_MSG_ID = 'xXqNEdtabhOl7E9driRsMNXyAgi16daqjuB8e24TXzE';

    // 给模板消息的参数赋值，然后调用发送模板消息的方法
    // $order 订单实体对象
    // $tplJumpPage 点击消息后跳转到小程序的哪个页面
    public function sendDeliveryMessage($order, $tplJumpPage=''){
        if (!$order){
            throw new OrderException();
        }
        $this->tpID = self::DELIIVERY_MSG_ID;
        $this->formID = $order->prepay_id;
        $this->page = $tplJumpPage;
        $this->prepayMessageData($order);
        $this->emphasisKeyword = 'keyword.DATA';
        return parent::sendMessage($this->getUserOpenID($order->user_id));
    }

    //模板内容
    public function prepayMessageData($order){
        $dt = new \DateTime();
        $data = [
            'keyword1' => [
                'value' => '京东快递'
            ],
            'keyword2' => [
                'value' => $order->snap_name
            ],
            'keyword3' => [
                'value' => $order->order_no
            ],
            'keyword4' => [
                'value' => $dt->format("Y-m-d H:i")
            ]
        ];
        $this->data = $data;
    }

    // 获取用户的openid
    public function getUserOpenID($uid){
        $user = User::get($uid);
        if (!$user){
            throw new UserException();
        }
        return $user->openid;
    }
}